package com.linhngua.code.xml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class SchemaValidator {
	
	public static boolean validate(String schemaFile, String xmlFile) {

		StringErrorHandler handler = new StringErrorHandler();
		try {
			DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
			fac.setAttribute(
					"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
					"http://www.w3.org/2001/XMLSchema");
			fac.setAttribute(
					"http://java.sun.com/xml/jaxp/properties/schemaSource",
					new File(schemaFile));
			fac.setValidating(true);
			DocumentBuilder b = fac.newDocumentBuilder();
			b.setErrorHandler(handler);
			b.parse(xmlFile);
		}
		catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
		
		return handler.exceptionCollector.size() == 0;
	}
	
	public static boolean validateContent(String schemaFile, String xmlContent) {

		StringErrorHandler handler = new StringErrorHandler();
		try {
			DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
			fac.setAttribute(
					"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
					"http://www.w3.org/2001/XMLSchema");
			fac.setAttribute(
					"http://java.sun.com/xml/jaxp/properties/schemaSource",
					new File(schemaFile));
			fac.setValidating(true);
			DocumentBuilder b = fac.newDocumentBuilder();
			
			b.setErrorHandler(handler);
			b.parse(new ByteArrayInputStream(xmlContent.getBytes()));
		}
		catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
		
		return handler.exceptionCollector.size() == 0;
	}
	
	static class StringErrorHandler implements ErrorHandler {
		
		List<Exception>	exceptionCollector	= new ArrayList<Exception>();
		
		public void warning(SAXParseException exception) throws SAXException {

			exceptionCollector.add(exception);
			exception.printStackTrace();
			
		}
		
		public void error(SAXParseException exception) throws SAXException {

			exceptionCollector.add(exception);
			exception.printStackTrace();
		}
		
		public void fatalError(SAXParseException exception) throws SAXException {

			exceptionCollector.add(exception);
			exception.printStackTrace();
		}
		
	}
}
